import { ref } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { ElMessage } from "element-plus";
 // 一定要安全密钥先写在前，key在后，不然无效
window._AMapSecurityConfig = {
    securityJsCode: "56551451381fa35caeee152ca2becd18",
}
export const useAMap = (mapContainer, searchKeyword) => {
  const selectedPoint = ref(null);
  const selectedPlaceName = ref("");
  let map = null;
  let marker = null;
  let placeSearch = null;
  let AMapClass = null;

  // 预加载地图API
  const loadMapAPI = async () => {
    try {
      return await AMapLoader.load({
        key: "632eb5d3be924a711208c802afd65ddf",
          // 添加安全密钥
        version: "2.0",
        plugins: [
          "AMap.ToolBar",
          "AMap.Scale",
          "AMap.Geolocation",
          "AMap.PlaceSearch",
          "AMap.AutoComplete",
          "AMap.MapType",
          "AMap.Geocoder" // 添加地理编码器插件
        ],
      });
    } catch (error) {
      console.error("高德地图API加载失败:", error);
      ElMessage.error("地图API加载失败，请检查网络连接");
      throw error;
    }
  };

  // 初始化地图
  const initMap = async () => {
    if (!mapContainer.value) return;

    AMapClass = await loadMapAPI();

    map = new AMapClass.Map(mapContainer.value, {
      zoom: 14,
      viewMode: "2D",
      resizeEnable: true,
      doubleClickZoom: false,
    });

    // 添加控件
    map.addControl(new AMapClass.ToolBar());
    map.addControl(new AMapClass.Scale());
    map.addControl(new AMapClass.MapType());
    map.addControl(
      new AMapClass.Geolocation({ position: "RB", offset: [10, 80] })
    );
    placeSearch = new AMapClass.PlaceSearch({
      pageSize: 1,
      pageIndex: 1,
      city: "全国",
    });

    map.on("click", handleMapClick);
  };

  // 处理地图点击事件
  const handleMapClick = (e) => {
    if (!e?.lnglat) return;
    const lng = e.lnglat.getLng();
    const lat = e.lnglat.getLat();
    console.log(AMapClass);
    
    if (AMapClass?.Geocoder) {
      const geocoder = new AMapClass.Geocoder();
      geocoder.getAddress([lng, lat], (status, result) => {
        const address = status === "complete" && result.regeocode 
          ? result.regeocode.formattedAddress 
          : "";
        selectedPlaceName.value = address;
        
        // 只更新标记，不移动地图中心点
        if (marker) {
          map.remove(marker);
        }
        marker = new AMapClass.Marker({
          position: [lng, lat],
          animation: "AMAP_ANIMATION_DROP"
        });
        map.add(marker);
        
        // 返回完整位置信息
        selectedPoint.value = { 
          longitude:lng, 
          latitude:lat, 
          name: address,
          fullAddress: result?.regeocode?.formattedAddress || "",
          adcode: result?.regeocode?.addressComponent?.adcode || "",
          province: result?.regeocode?.addressComponent?.province || "",
          city: result?.regeocode?.addressComponent?.city || "",
          district: result?.regeocode?.addressComponent?.district || ""
        };
      });
    } else {
      // 没有地理编码器时的处理
      if (marker) {
        map.remove(marker);
      }
      marker = new AMapClass.Marker({
        position: [lng, lat],
        animation: "AMAP_ANIMATION_DROP"
      });
      map.add(marker);
      selectedPoint.value = { lng, lat, name: "" };
    }
  };

  // 设置标记和中心点
  const setMarkerAndCenter = (lng, lat, name = "", moveCenter = true) => {
    if (marker) {
      map.remove(marker);
    }
    marker = new AMapClass.Marker({
      position: [lng, lat],
      animation: "AMAP_ANIMATION_DROP",
    });
    map.add(marker);
    if (moveCenter) {
      map.setCenter([lng, lat]);
    }
    selectedPoint.value = { lng, lat, name: name || selectedPlaceName.value };
  };

  // 处理搜索
  const handleSearch = (keyword) => {
    console.log(keyword);
    if (!keyword) return;
    placeSearch.search(keyword, (status, result) => {
        console.log(status);
        console.log(result);

      if (
        status === "complete" &&
        result.info === "OK" &&
        result.poiList?.pois?.length
      ) {
        const poi = result.poiList.pois[0];
        selectedPlaceName.value = poi.name;
        console.log(selectedPlaceName);
        
        // 明确传递 moveCenter 为 false，避免地图移动
        setMarkerAndCenter(poi.location.lng, poi.location.lat, poi.name); 
      } else {
        ElMessage.warning("未找到相关地点");
      }
    });
  };

  // 打开地图弹窗
  const openDialog = async (position) => {
    if (!map) {
      await initMap();
    }
    if (position?.lng && position?.lat) {
      // 明确传递 moveCenter 为 false，避免地图移动
      setMarkerAndCenter(position.lng, position.lat, ''); 
    } else {
      // 尝试获取当前位置
      if (navigator.geolocation) {
        await new Promise((resolve, reject) => {
          navigator.geolocation.getCurrentPosition(
            (pos) => {
              const { longitude, latitude } = pos.coords;
              setMarkerAndCenter(longitude, latitude, ''); 
              resolve();
            },
            (error) => {
              // 获取失败时，使用默认定位（可以根据需要调整）
            //   map.setCenter();
            },
          );
        });
      } else {
        // 浏览器不支持地理位置 API 时，使用默认定位
        map.setCenter();
      }
    }
  };

  // 销毁地图
  const destroyMap = () => {
    if (map) {
      map.destroy();
      map = null;
      marker = null;
    }
  };

  // 清除地图上的标记
  const clearMarker = () => {
    if (marker) {
      map.remove(marker);
      marker = null;
    }
    selectedPoint.value = null;
    selectedPlaceName.value = '';

  };

  return {
    selectedPoint,
    openDialog,
    destroyMap,
    handleSearch,
    handleMapClick,
    clearMarker // 导出清除标记的方法
  };
};
